﻿using Fuse8.ContentManagementFramework.Administration.Models;
using Fuse8.ContentManagementFramework.BizFacade.Services;
using Fuse8.ContentManagementFramework.Domain.Special;
using Fuse8.ContentManagementFramework.Web.ApplicationRuntime;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace Fuse8.ContentManagementFramework.Administration.Controllers
{
    public class CmsMediaContentController : CmsAdminController
    {
        private readonly CmsMediaContentService _mediaContentService = new CmsMediaContentService();

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Add(int? id)
        {
            ViewBag.BackToMedia = !id.HasValue;

            if (id.HasValue)
            {
                ViewBag.MediaContentId = id.Value;
            }

            return View();
        }

        [HttpPost]
        public ActionResult Add(CmsAdminMediaContentModel model)
        {
            ActionResult result = null;

            string returnUrl = model.MediaId > 0 ?
                Url.Action("Get", "cmsmedia", new { id = model.MediaId }) :
                Url.Action("index", "cmsmedia");

            string error = string.Empty;
            if (model != null)
            {
                if (ModelState.IsValid)
                {
                    _mediaContentService.AddMany(model.Contents, model.MediaId);

                    result = Request.IsAjaxRequest() ?
                        Json(new { result = 1, url = returnUrl }) :
                        RedirectToAction("index", "cmsmedia") as ActionResult;
                }
                else
                {
                    error = ModelState
                        .SelectMany(p => p.Value.Errors)
                        .Select(p => p.Exception.Message)
                        .Aggregate(
                            (working, next) =>
                            {
                                return string.Format("{0} {1}", working, next);
                            });
                }
            }
            else
            {
                error = "Model is empty";
            }

            return result ?? (Request.IsAjaxRequest() ? Json(new { result = error, url = returnUrl }) : new EmptyResult() as ActionResult);
        }

        [HttpGet]
        public ActionResult Edit(int id)
        {
            var mediaContent = _mediaContentService.FindOne(id);

            var content = new CmsAdminMediaContent()
                                           {
                                               Description = mediaContent.Description,
                                               MetaCode = mediaContent.MetaCode,
                                               Name = mediaContent.MediaContentName,
                                               BlockFromSearchEngines = mediaContent.BlockFromSearchEngines
                                           };
            var model = new CmsAdminMediaContentModel()
                            {
                                Contents = new List<CmsAdminMediaContent>() { content },
                                MediaId = mediaContent.MediaId,
                                Id = id
                            };

            SetFolders();

            return View(model);
        }

        [HttpPost]
        public ActionResult Edit(CmsAdminMediaContentModel model, HttpPostedFileBase file)
        {
            var media = _mediaContentService.FindOne(model.Id);
            if (file != null)
            {
                var uploader = new FileUploader(file.FileName, Request.Files, Session);
                uploader.Upload(0, 0, media.MainFile.Id);
            }
            if (model.Contents != null && model.Contents.Count > 0)
            {
                var content = model.Contents[0];
                media.MetaCode = content.MetaCode;
                media.MediaId = model.MediaId;
                media.MediaContentName = content.Name;
                media.Description = content.Description;
                media.BlockFromSearchEngines = content.BlockFromSearchEngines;
                _mediaContentService.Save(media);
            }

            return RedirectToAction("Get", "CmsMedia", new { id = media.MediaId });
        }

        public ActionResult UploadFile()
        {
            return Request.IsAjaxRequest() ?
                PartialView() as ActionResult :
                View();
        }

        [HttpPost]
        public ActionResult UploadFile(int? chunk, int? chunks, string name)
        {
            var data = new FileUploader(name, Request.Files, Session)
                .Upload(chunk ?? 0, chunks ?? 1);

            return Json(
                new
                {
                    IsFileUploaded = data != null,
                    FileId = data != null ? data.Id : 0,
                    LinkedFileName = data != null ? data.LinkedFileName : string.Empty,
                    IsImage = data != null && data.IsImage,
                    FileType = data != null ? data.FileType : "unknown",
                    BlockFromSearchEngines = false
                },
                "text/plain",
                Encoding.UTF8);
        }

        [HttpPost]
        public ActionResult Action(CmsAdminMediaActionModel model)
        {
            if ((model != null) && !string.IsNullOrEmpty(model.Action))
            {
                if (model.Action.Equals(CmsAdminMediaActionModel.ActionDelete, StringComparison.OrdinalIgnoreCase))
                {
                    if (model.MediaContent.Any())
                    {
                        int mediaFileId = 0;
                        foreach (var item in model.MediaContent)
                        {
                            var indentificatorParts = item.Split(new string[] { CmsAdminMediaActionModel.MediaContentIdentificatorSplitter }, StringSplitOptions.RemoveEmptyEntries);
                            if (indentificatorParts.Length == 2)
                            {
                                if (int.TryParse(indentificatorParts[0], out mediaFileId))
                                {
                                    _Delete(mediaFileId);
                                }

                                DeleteMediaFile(indentificatorParts[1]);
                            }
                        }
                    }
                }
            }

            return model != null ?
                RedirectToAction("get", "cmsmedia", new { id = model.Id }) :
                RedirectToAction("index", "cmsmedia");
        }

        protected override bool _Delete(int id)
        {
            var media = _mediaContentService.FindOne(id);
            if (media != null && media.MainFile != null)
            {
                media.MainFile.Remove();
            }
            _mediaContentService.Remove(id);

            return true;
        }
    }
}